#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QHostAddress>
#include <QString>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port->setText("8899");
    ui->IP->setText("127.0.0.1");
    setWindowTitle("客户端");

    ui->disconnect->setDisabled(true);
    //创建监听的服务器对象
    m_tcp = new QTcpSocket;
    connect(m_tcp , &QTcpSocket::readyRead , this ,[=](){
        QByteArray data =m_tcp->readAll();
        ui->record->append("服务器："+ data );
    });
    connect(m_tcp , &QTcpSocket::disconnected , this  , [=](){
        m_tcp->close();
        m_tcp->deleteLater();  //delete m_tcp
        m_status->setPixmap(QPixmap(":/pic/yes.png").scaled(20,20));   //检测到连接后换连接状态
        ui->connect->setDisabled(false);
        ui->connect->setDisabled(true);
        //检测是否可以接受数据
        ui->record->append("已断开连接");
    });
    connect(ui->connect,&QPushButton::clicked , this  , &MainWindow::on_connect_clicked );
    connect(ui->send_message,&QPushButton::clicked , this , &MainWindow::on_send_message_clicked);

    connect(m_tcp , &QTcpSocket::connected , this ,[=](){
        m_status->setPixmap(QPixmap(":/pic/no.png").scaled(20,20));
        ui->record->append("成功连接到服务器");
        ui->connect->setDisabled(true);
        ui->connect->setDisabled(false);
    });
    //状态类
    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/pic/no.png").scaled(20,20));  //用scaled方法对图片进行缩放
    ui->statusbar->addWidget(new QLabel("连接状态："));
    ui->statusbar->addWidget(m_status);
}


void MainWindow::on_connect_clicked(){
    QString ip = ui->IP->text();
    unsigned short port =ui->port->text().toUShort();
    m_tcp->connectToHost(QHostAddress(ip) , port);
}

void MainWindow::on_send_message_clicked(){
    QString message = ui->record_2->toPlainText();
    m_tcp->write(message.toUtf8());
    ui->record->append("客户端："+ message );
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_disconnect_clicked()
{
    m_tcp->close();
    ui->connect->setDisabled(false);
    ui->connect->setDisabled(true);
}

